package itxx.itxx.servlet;

import itxx.itxx.bean.Student;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;

/*实现添加的功能*/
@WebServlet("/AddStudnetServlet")
public class AddStudnetServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //获取表单数据
        String username = request.getParameter("username");
        String age = request.getParameter("age");
        String sorce = request.getParameter("sorce");
        //创建学生对象并赋值
        Student stu = new Student(username, Integer.parseInt(age), Integer.parseInt(sorce));
        stu.setName(username);
        stu.setAge(Integer.parseInt(age));
        stu.setSorce(Integer.parseInt(sorce));
        //将学生对象的数据保存在D:\\stu.txt文件中
        //BufferedInputStream bis = new BufferedInputStream(new FileInputStream("D:\\develop\\workspace\\Web_Code\\reqresp_test\\src"));
        BufferedWriter bw = new BufferedWriter(new FileWriter("D:\\stu.txt",true));
        bw.write(stu.getName()+","+stu.getAge()+","+stu.getSorce());
        bw.newLine();
        //释放资源
        bw.close();
        //通过定时刷新功能响应给浏览器
        response.setContentType("text/html;charset=UTF-8");
        response.getWriter().write("添加成功,3秒后自动跳转到首页");
        response.setHeader("Refresh","3;URL=index.html");



    }
}
